package be.vdab.listeners;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * Application Lifecycle Listener implementation class MandjeListener
 *
 */
//@WebListener
public class MandjeListener implements HttpSessionAttributeListener {
	private static final String MANDJE = "mandje";
	private static final String AANTAL_MANDJES = "aantalMandjes";

    /**
     * Default constructor. 
     */
    public MandjeListener() {
        // TODO Auto-generated constructor stub
    }

	@Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if (event.getName().equals(MANDJE)) {
        	verlaagMandjeTeller(event.getSession().getServletContext());
        }
    }
	private synchronized void verlaagMandjeTeller(ServletContext servletContext) {
		Integer mandjeTeller = (Integer) servletContext.getAttribute(AANTAL_MANDJES);
		mandjeTeller--;
		servletContext.setAttribute(AANTAL_MANDJES, mandjeTeller);
	}

	/**
     * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
     */
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
    	if (event.getName().equals(MANDJE)) {
    		verhoogMandjeTeller(event.getSession().getServletContext());
    	}
    }
    private synchronized void verhoogMandjeTeller( ServletContext servletcontext) {
    	Integer mandjeTeller = (Integer) servletcontext.getAttribute(AANTAL_MANDJES);
    	if (mandjeTeller == null) {
    		mandjeTeller = 1;
    	} else {
    		mandjeTeller++;
    	}
    	servletcontext.setAttribute(AANTAL_MANDJES, mandjeTeller);
    }

	/**
     * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
     */
    public void attributeReplaced(HttpSessionBindingEvent event) {
       
    }
	
}
